package com.mashibing.controller;

import com.mashibing.internalcommon.request.PushRequest;
import com.mashibing.internalcommon.util.SsePrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class SseController {

    public static Map<String, SseEmitter> map = new HashMap<>();

    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam Long userId, @RequestParam String identity) {
        System.out.println("用户id=" + userId + "用户身份=" + identity);
        SseEmitter sseEmitter = new SseEmitter(0L);

        String mapKey = SsePrefixUtils.generatorSseKey(userId, identity);

        map.put(mapKey, sseEmitter);
        log.info("此时map为{}",map);
        return sseEmitter;
    }

    @PostMapping("/push")
    public String push(@RequestBody PushRequest pushRequest) {

        Long userId = pushRequest.getUserId();
        String identity = pushRequest.getIdentity();
        String content = pushRequest.getContent();

        String mapKey = SsePrefixUtils.generatorSseKey(userId, identity);
        SseEmitter sseEmitter = map.get(mapKey);

        if (sseEmitter == null) {
            log.info("连接已关闭");
            return "连接已关闭";
        }

        try {
            sseEmitter.send(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("向身份为{}，id为{}的user发送消息成功，消息内容为{}",identity,userId,content);
        return "发送成功：content=" + content;
    }

    @GetMapping("/close")
    public String close(@RequestParam Long userId, @RequestParam String identity) {
        String mapKey = SsePrefixUtils.generatorSseKey(userId, identity);

        SseEmitter sseEmitter = map.get(mapKey);
        if (null != sseEmitter) {
            map.remove(mapKey);
        }
        return "关闭连接成功：userId=" + userId;
    }

}
